from app.models.product import Product
from app import db

class ProductService:
    def get_all_products(self):
        products = Product.query.all()
        return [{
            'id': p.id,
            'name': p.name,
            'description': p.description,
            'price': p.price,
            'stock': p.stock,
            'image_url': p.image_url
        } for p in products]
    
    def get_product_by_id(self, product_id):
        product = Product.query.get_or_404(product_id)
        return {
            'id': product.id,
            'name': product.name,
            'description': product.description,
            'price': product.price,
            'stock': product.stock,
            'image_url': product.image_url
        }
    
    def create_product(self, data):
        product = Product(
            name=data['name'],
            description=data.get('description'),
            price=data['price'],
            stock=data.get('stock', 0),
            image_url=data.get('image_url')
        )
        
        db.session.add(product)
        db.session.commit()
        
        return {
            'id': product.id,
            'name': product.name,
            'description': product.description,
            'price': product.price,
            'stock': product.stock,
            'image_url': product.image_url
        }
    
    def update_product(self, product_id, data):
        product = Product.query.get_or_404(product_id)
        
        product.name = data.get('name', product.name)
        product.description = data.get('description', product.description)
        product.price = data.get('price', product.price)
        product.stock = data.get('stock', product.stock)
        product.image_url = data.get('image_url', product.image_url)
        
        db.session.commit()
        
        return {
            'id': product.id,
            'name': product.name,
            'description': product.description,
            'price': product.price,
            'stock': product.stock,
            'image_url': product.image_url
        }
    
    def delete_product(self, product_id):
        product = Product.query.get_or_404(product_id)
        db.session.delete(product)
        db.session.commit()
        return {'message': '商品已删除'} 